/**
 * @copyright   2008-2015 简好网络 <http://www.phpshe.com>
 * @creatdate   2010-1001 koyshe <koyshe@gmail.com>
 */

(function($){
	$.fn.city_select = function(config) {
		//默认值
		var config = $.extend({
			prov : null,
			city : null,
			area : null,
		}, config);
		var _this = this;
		var _prov = _this.find(".js_prov");
		var _city = _this.find(".js_city");
		var _area = _this.find(".js_area");
		var prov = config.prov;
		var city = config.city;
		var area = config.area;
		var city_list = [];
		var area_list = [];
		//省份显示
		var prov_show = function() {
			city_list = [];
			var html = '<option value="">请选择省</option>';
			for (var i in city_data[0]) {
				var province_id = city_data[0][i].id;
				var province_name = city_data[0][i].name;
				var province_nameshow = city_data[0][i].nameshow == undefined ? city_data[0][i].name : city_data[0][i].nameshow;
				if (province_name == prov) {
					city_list = city_data[province_id];
					html += '<option value="'+province_name+'" selected="selected">'+province_nameshow+'</option>';
				}
				else {
					html += '<option value="'+province_name+'">'+province_nameshow+'</option>';
				}
			}
			_prov.html(html);
			city_show();
		}
		//城市显示
		var city_show = function() {
			area_list = [];
			var html = '<option value="">请选择市</option>';
			for (var i in city_list) {
				var city_id = city_list[i].id;
				var city_name = city_list[i].name;
				var city_nameshow = city_list[i].nameshow == undefined ? city_list[i].name : city_list[i].nameshow;
				if (city_name == city) {
					area_list = city_data[city_id];
					html += '<option value="'+city_name+'" selected="selected">'+city_nameshow+'</option>';
				}
				else {
					html += '<option value="'+city_name+'">'+city_nameshow+'</option>';
				}
			}
			_city.html(html);
			area_show();
		}
		//区县显示
		var area_show = function() {
			var html = '<option value="">请选择区县</option>';
			for (var i in area_list) {
				var area_id = area_list[i].id;
				var area_name = area_list[i].name;
				var area_nameshow = area_list[i].nameshow == undefined ? area_list[i].name : area_list[i].nameshow;
				if (area_name == area) {
					html += '<option value="'+area_name+'" selected="selected">'+area_nameshow+'</option>';
				}
				else {
					html += '<option value="'+area_name+'">'+area_nameshow+'</option>';
				}
			}
			_area.html(html);
		}
		//绑定省份更改
		_prov.live("change", function(){
			prov = _prov.find("option:selected").val();
			prov_show();
		});
		//绑定城市更改
		_city.live("change", function(){
			city = _city .find("option:selected").val();
			city_show();
		});	
		prov_show();
	}
})(jQuery);